
import React from "react";
import { loadStripe } from "@stripe/stripe-js";
import {
  PaymentElement,
  Elements,
  useStripe,
  useElements,
} from "@stripe/react-stripe-js";
import { Button } from "@/components/ui/button";

const stripePromise = loadStripe(
  "pk_test_51Q2caaKSmEcUB3xND5I03YVfCZw0qw4x8s5Jl2seJAbH9NJxW2xi358dEoWhJussjv8QSWhDVP1kTXZplsRsizpZ00gUNhMThD"
);

function CheckoutForm() {
  const stripe = useStripe();
  const elements = useElements();

  const [errorMessage, setErrorMessage] = React.useState("");
  const [isLoading, setIsLoading] = React.useState(false);

  const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!stripe || !elements) {
      // Stripe.js hasn't yet loaded.
      // Make sure to disable form submission until Stripe.js has loaded.
      return;
    }

    setIsLoading(true);
    console.log(window.location.hostname);
    const { error } = await stripe.confirmPayment({
      elements,
      confirmParams: {
        // TODO 这里需要修改跳转的位置
        return_url: "https://www.flexui.cn/subscription"
      },
    });
    console.log(error);
    if (error.type === "card_error" || error.type === "validation_error") {
      setErrorMessage(error?.message ?? "");
    } else {
      setErrorMessage("An unexpected error occurred.");
    }

    setIsLoading(false);
  };

  return (
    <form onSubmit={handleSubmit}>
      <PaymentElement />
      <Button
        disabled={isLoading || !stripe || !elements}
        id="submit"
        className="mt-4"
      >
        <span id="button-text">
          {isLoading ? <div className="spinner" id="spinner"></div> : "Pay now"}
        </span>
      </Button>
      {errorMessage && <div>{errorMessage}</div>}
    </form>
  );
}

export default function PaymentForm({
  clientSecret,
}: {
  clientSecret: string;
}) {
  // const appearance = {
  //     theme: 'stripe',
  // };
  const options = {
    clientSecret,
    // appearance,
  };
  return (
    <Elements options={options} stripe={stripePromise}>
      <CheckoutForm />
    </Elements>
  );
}
